package com.datastructure.search.binarysearch;

import java.util.ArrayList;
import java.util.List;

public class BinarySearch {

    public static void main(String[] args) {
        int arr[] = {1,8,10,89,1000,1000,1000,1234};

        // int resIndex = binarySearch(arr, 0, arr.length-1, 89);
        // System.out.println("resIndex=" + resIndex);
        List<Integer> resIndexList = binarySearch2(arr, 0, arr.length-1, 1000);
        System.out.println("resIndexList=" + resIndexList);
    }

    public static int binarySearch(int[] arr, int left, int right, int findVal){
        // 当left > right 时，说明递归整个数组，但是没有找到
        if(left > right){
           return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if(findVal > midVal){ // 向右递归
            return binarySearch(arr, mid + 1,right,findVal);
        } else if (findVal < midVal){
            return binarySearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

    public static List<Integer> binarySearch2(int[] arr, int left, int right, int findVal){
        // 当left > right 时，说明递归整个数组，但是没有找到
        if(left > right){
            return new ArrayList<>();
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if(findVal > midVal){ // 向右递归
            return binarySearch2(arr, mid + 1,right,findVal);
        } else if (findVal < midVal){
            return binarySearch2(arr, left, mid - 1, findVal);
        } else {
            List<Integer> resIndexList = new ArrayList<>();
            int temp = mid - 1;
            // 退出
            while (temp >= 0 && arr[temp] == findVal) {
                // 否则就把temp放入到resIndexList
                resIndexList.add(temp);
                temp -= 1; // temp左移
            }
            resIndexList.add(mid);
            // 向mid索引值的右边扫描，将所有满足1000的元素的下标，加入到集合ArrayList
            temp = mid + 1;
            // 退出
            while (temp <= arr.length - 1 && arr[temp] == findVal) {
                // 否则就把temp放入到resIndexList
                resIndexList.add(temp);
                temp += 1; // temp右移
            }
            return resIndexList;
        }
    }
}
